package com.tencent.wepay.protocol.domain;

import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

import com.tencent.wepay.annotation.SignIgnore;
import com.tencent.wepay.handler.xml.XStreamHandler;
import com.tencent.wepay.util.SignUtil;
import com.thoughtworks.xstream.annotations.XStreamAlias;

public class XStreamDomain extends Validation{
	public Map<String,Object> getSignMap(){
		Map<String, Object> params = new TreeMap<String, Object>(
		     new Comparator<String>() {
		          public int compare(String obj1, String obj2) {
		              // 降序排序
		              return obj1.compareTo(obj2);
		          }
		     }
		);	
		Field[] fields=getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			XStreamAlias xStreamAlias=field.getAnnotation(XStreamAlias.class);
			if(field.getAnnotation(SignIgnore.class)!=null||xStreamAlias==null){
				continue;
			}
			String key=xStreamAlias.value();
			try {
				Object value=field.get(this);
				if(value!=null){
					params.put(key, value);
				}
			}catch(Exception e){
			}
		}
		return params;
	}
	public String toSign(String key){
		Map<String,Object> map=getSignMap();
		StringBuffer str=new StringBuffer();
		for(Map.Entry<String,Object> entry:map.entrySet()){
            if(entry.getValue()!=""){
            	str.append(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
		str.append("key="+key);
		return SignUtil.md5(str.toString());
	}
	public String toXML(){
		return XStreamHandler.toXML(this);
	}
}
